;
(function (call) {
    var zcqfx = {
        selectedPro: null,
        playList: null,
        latestTime: null,
        iframeSrc: '', //中长期分析iframe地址
        apTpClusterList: [], //ap降水列表
        apGh500ClusterList: [], //ap高度场列表
        currentCluster: '',
        period: '',
        targetId: '',
        time: '',
        count: 0,
        router: {
            cfg: "/business/zcqfx.json",
            picData:[],	
            getLatestTime: 'sjyb/queryModelGridDataLatestTime',
            clusterList: '/raw/ysqMakeImg/clusterList'
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
					$(".product-zcqfx-list li:eq(0)").click();
                }
            });
        },
        // 获取最新起报时间
        getLatestTime: function (call) {
            var that = this;
			let hours = new Date().getHours();
			if(hours<8){
				//昨天08
				const currentDate = new Date();
				currentDate.setDate(currentDate.getDate() - 1);
				that.latestTime = new Date(currentDate).format('yyyy-MM-dd 08:00:00')
			}else if(hours>=8 && hours<18){
				//昨天20
				const currentDate = new Date();
				currentDate.setDate(currentDate.getDate() - 1);
				that.latestTime = new Date(currentDate).format('yyyy-MM-dd 20:00:00')
			}else{
				//今天08
				const currentDate = new Date();
				that.latestTime = new Date(currentDate).format('yyyy-MM-dd 08:00:00')
			}
            let modeId = $(".product-zcqfx-tab li.active").data('model').id;
            if (modeId === 'ecc6f') { //只有周一、周四起报
                const currentDate = new Date();
                const dayOfWeek = currentDate.getDay();
                if (dayOfWeek === 1) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 4).format('yyyy-MM-dd 08:00:00');
                }
                if (dayOfWeek === 2) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 5).format('yyyy-MM-dd 08:00:00');
                }

                if (dayOfWeek === 3) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 2).format('yyyy-MM-dd 08:00:00');
                }
                if (dayOfWeek === 4) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 3).format('yyyy-MM-dd 08:00:00');
                }
                if (dayOfWeek === 5) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 4).format('yyyy-MM-dd 08:00:00');
                }

                if (dayOfWeek === 6) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 2).format('yyyy-MM-dd 08:00:00');
                }
                if (dayOfWeek === 0) {
                    that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000 * 3).format('yyyy-MM-dd 08:00:00');
                }
            }

            if (modeId === 'ece6f') {
                const currentDate = new Date();
                that.latestTime = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000).format('yyyy-MM-dd 08:00:00');
            }

			if (call)
                call();
            /** var modeType = $(".product-zcqfx-tab li.active").data('model').fullname;
            var param = {
                modeType: modeType
            };
            $.ajax({
				url: this.router.getLatestTime,
				type: 'GET',
				dataType: 'json',
				data: param,
			}).done(function (res) {
				if (res.isSuccess)
					that.latestTime = res.data;
				if (call)
					call();
			})**/
           
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            if (data.pro_type.global) {
                that.buildModel(data, data.pro_type.global, "集合预报：")
            }
            if (data.pro_type.area) {
                that.buildModel(data, data.pro_type.area, "确定预报：")
            }
            if (data.pro_type.hundred) {
                that.buildModel(data, data.pro_type.hundred, "延伸预报：")
            }
			if (data.pro_type.zhishu) {
                that.buildModel(data, data.pro_type.zhishu, "环流指数：")
            }
            if (data.pro_type.heatingConsultation) {
                that.buildModel(data, data.pro_type.heatingConsultation, '会&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;商：')
            }
            $(".product-zcqfx-tab").show();
        },
        //构建模式
        buildModel: function (data, selfData, text) {
            var that = this;
            var $div = $('<div></div>');
            var $span = $('<span>' + text + '</span>');
            $div.append($span);
            var $childDiv = $('<div></div>');
            $div.append($childDiv);
            var $ul = $('<ul></ul>');
            selfData.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
					let targeturl = $(this).data("model").targetUrl;
                    that.targetId = $(this).data("model").id;
                    that.iframeSrc = $(this).data('model').iframeSrc || '';
					if (targeturl) {
						$(".product-zcqfx-pic,.product-zcqfx-datepicker,.product-zcqfx-datechange,.product-zcqfx-interval,.product-zcqfx-list").hide();
						$(".product-zcqfx-iframe").show().attr("src",targeturl);
						$(".product-zcqfx-tab .active").removeClass("active");
						$(this).addClass("active");
					} else {
						$(".product-zcqfx-pic,.product-zcqfx-datepicker,.product-zcqfx-datechange,.product-zcqfx-interval,.product-zcqfx-list,.a-m-container").show();
						$(".product-zcqfx-iframe").hide();

						that.delAllLayer(); //切换模式后, 清空之前模式数据
						$(".product-zcqfx-tab li").removeClass("active");
						$(this).addClass("active");

						$('.product-zcqfx-datepicker').empty()
							.append(`
							<div class="date-panel">
								<input class="DateAgent" id="date" data-options="${item.dateOptions}" value="">
								<i class="btn-forward"></i>
								<i class="btn-backward"></i>
								<i class="btn-newest"></i>
							</div>`);
						$.IDate(".product-zcqfx-datepicker .date-panel", {
							query: function query() {
								zcqfx.buildLastTime(function () {
									zcqfx.getMultiGridData();
								});
							}
						});
						that.getLatestTime(function () {
							if (that.latestTime) {
								$(".product-zcqfx-datepicker #date").IDatePicker().setVal(that.latestTime);
								that.buildLastTime();
								that.buildProContent(data.basic_pro[item.id] || []);
							}
						});
					}
                    
                    if (that.targetId === 'ap') { //ap聚类高度场当前时间没有数据需要-12小时，
                        $(".product-zcqfx-datepicker .btn-forward").click();
                    }

                    that.targetId === 'heatingConsultation' && $('#a-m-timeline').hide();
                })
                $ul.append($li);
            })
            $childDiv.append($ul);
            $(".product-zcqfx-tab").append($div);
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-zcqfx-list").empty();
            let modeId = $(".product-zcqfx-tab li.active").data('model').id;
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);

                if (item.checkbox) {
                    $title.append(`<div class="product-correlated"><input type=checkbox ${item.checkbox.checked ? "checked" : ""}>${item.checkbox.name}</div>`);
                }
                $item.append($title);
                if (item.content) {
                    if (!item.height) {
                        var $ul = $('<ul>');
                        if (item.group_id) $ul = $('<ul>').attr('id', item.group_id);
                        if (item.group_id == 'custom') {
                            $ul = $('<ul>').addClass('product-pic-tab')
                        }
                        item.content.forEach(function (pro) {
                            let $span = $(`<span>${pro.ele_name}</span>`);
                            let $li = null;

                            if (pro.optionId) {
                                let $select = $(`<select id=${pro.optionId} style="margin-left: 10px;"></div>`).change(function() {
                                    that.currentCluster = $(this).val();
                                    that.changeIframeSrc();
                                });
                                $select.append('<option value="" disabled selected>请选择</option>');
                                $li = $(`<li style="display: flex;"></li>`).append($span).append($select);
                            } else {
                                $li = $(`<li></li>`).attr('id', pro.ele_id).append($span);
                            }
                            
                            if (pro.selected) {
                                // $li.addClass("default");
                                if (modeId === 'heatingConsultation') {
                                    $li.addClass('default active');
                                } else {
                                    $li.addClass("default");
                                }
                            }
                            if (item.maxHour)
                                pro.maxHour = item.maxHour; 
                            $li.data('pro', pro);
                            if (pro.title)
                                $li.attr('title', pro.title);
                            if (pro.width)
                                $li.css("width", pro.width);
                            $ul.append($li);
                        })
                        $item.append($ul);
						if(item.group_needthrad){
							$item.append($("<div>").addClass("addition_condition_title").text(item.group_hradName));
							var $theaddatazi = $("<div>").addClass("addition_condition_container");
							var theadData = item.group_theadData;
							theadData.forEach(function (pro2) {
								let $div = $("<div>").addClass("addition_condition_item").attr("val",pro2.id).text(pro2.name).attr("item",pro2.item)
								$theaddatazi.append($div);
							})
							$item.append($theaddatazi);
						}
						
                    } else {
                        var $table = $(`<table id=${item.group_id}>`);
                        if (item.group_id == 'custom') {
                            $table.addClass('product-pic-tab')
                        }
                        var $thead = $('<tr>');
                        $thead.append('<th></th>');
                        item.height.forEach(function (h) {
                            $thead.append(`<th>${h}</th>`);
                        })
                        $table.append($thead);
                        item.content.forEach(function (pro) {
                            var $tr = $(`<tr id=${pro.ele_id}>`);
                            $tr.append(`<td>${pro.ele_name}</td>`);
                            item.height.forEach(function (h) {
                                var $td = $('<td>');
                                var newPro = $.extend({}, pro);
                                if (newPro.heights && -1 == $.inArray(h, newPro.heights)) {
                                    $td.addClass("disabled");
                                }
                                newPro.height = h;
                                newPro.interval = item.interval;
                                newPro.type = item.group_id;
                                newPro.count = 0;
                                $td.data('pro', newPro).attr('id', newPro.ele_id + h);
                                $tr.append($td);
                            })
                            $table.append($tr);
                        })
                        $item.append($table);
                    }
                }
                $(".product-zcqfx-list").append($item);
                modeId != 'heatingConsultation' && $(".product-zcqfx-list").find('li.default').trigger('click');
            });
            modeId === 'heatingConsultation' && this.changeHeatingConsultationIframeSrc();
        },
        // 初始化最近起报时间
        buildLastTime: function (call) {
            var interval = $(".product-zcqfx-tab li.active").data("model").interval;
			console.log(interval)
            var baseDate = $(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ":00";
            console.log('baseDate======>', baseDate);
            var newDate = new Date(baseDate);
            var liArr = [];
            let modeId = $(".product-zcqfx-tab li.active").data('model').id;
            if (modeId ==='ece6f') {
                for (var i = 0; i < 4; i++) {
                    liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                    newDate.setHours(newDate.getHours() + interval);
                }
                $(".product-zcqfx-datechange ul").empty().append(liArr.join(""));
            } else {
                for (var i = 0; i < 4; i++) {
                    liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                    newDate.setHours(newDate.getHours() - interval);
                }
                $(".product-zcqfx-datechange ul").empty().append(liArr.reverse().join(""));
            }
            

            if (call && this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;
            let mode = $(".product-zcqfx-tab .active").data("model").id; 
            if(mode == "ecjihe"){
                startTime = new Date(new Date(pro.time).getTime()+1000*60*60*Number(pro.ele.interval)).format("yyyy-MM-dd hh:00:00")
            }
            if(pro.ele.startHour){
                startTime = new Date(new Date(pro.time).getTime()+1000*60*60*Number(pro.ele.startHour)).format("yyyy-MM-dd hh:00:00")
            }
            console.log(startTime);
            var interval = pro.ele.interval * 60;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
				iszcqfx:true,
                maxHour: pro.ele.maxHour || 72,
                splitPoint: pro.ele.splitPoint || 72,
                pro: pro,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh',
                    timeInterval: 12,
                    customHm: [8, 20]
                },
                timeInterval: interval,
                layers: [],
                call: function (pro) {
                    let modeid = $(".product-zcqfx-tab .active").data("model").id;
                    if( modeid== "ecjihe"){
                        that.showpic(pro.clickTime);
                    }else if(modeid == "ec"){
                        pro.clickTime = new Date(pro.clickTime).format('yyMMddhh')
                        that.showecpic(pro);
                    }else{
                        that.getothermodePic(pro);
                    }
                },
                getPlayData: function (pro, timeArr) {
                    
                }
            });
            pro.forecastTime = that.playList.getCurTime();
        },
        getothermodePic:function(proInfo){
            var that = this;
            console.log("proInfo");
            console.dir(proInfo);
            let mode = $(".product-zcqfx-tab .active").data("model").id;
            var time = new Date($(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00').format("yyyyMMddhh0000");
            let period = (proInfo.clickTime - new Date($(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00').getTime())/(1000*60*60);
            if (mode === 'ece6f') {
                period = (proInfo.clickTime - new Date($(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00').getTime())/(1000*60*60) / 6;
            }
            that.period = period;
            that.time = time;
            
            console.log('this.selectedPro', that.selectedPro);
            if (!that.selectedPro.iframeSrc) {
                var param = {
                    time: time,
                    period:period,
                    element:proInfo.ele.ele_id
                }

                $.ajax({
                    url: '/raw/ysqMakeImg/ysqProductMakeImg',
                    type: 'POST',
                    data: param,
                }).done(function (res) {
                    $("#imgArea,.imgArea_top,#imgArea_imgLegend").hide();
                    $("#eccontain").show();
                    if(res && res!=""){
                        $("#ecpic").attr("src","data:image/png;base64," +res);
                    }else{
                        $("#ecpic").attr("src","http://10.226.120.45:8091/TJ/tianjin/resources/business/zhfx/skjc/kstwin/img/noData.png");
                    }
                })
            } else {
                let modeId = $(".product-zcqfx-tab li.active").data('model').id;
                if (modeId === 'heatingConsultation') {
                    this.changeHeatingConsultationIframeSrc();
                } else if (['ecjh', 'ecc6f', 'ece6f'].includes(modeId)) {
                    this.changeIframeSrc();
                } else {
                    this.selectedPro.ele_id === 'tp_cluster' && this.getTpClusterList(new Date(+time).getTime());
                    this.selectedPro.ele_id === 'gh500_cluster' && this.getGh500ClusterList(new Date(+time).getTime());
                    this.changeIframeSrc();
                }
            }
        },
		showpic:function(time){
			var that = this;
            $("#imgArea,.imgArea_top,#imgArea_imgLegend").show();
            $("#eccontain").hide();
			let data = that.picData.filter(item=>item.time == time);
			let title = new Date(time)+" EC集合"+that.selectedPro.ele_name;
			if(that.selectedPro.thred){
				title = title+"("+$(".addition_condition_item.active").text()+")";
			}
			title = title+" ("+that.selectedPro.unit+")";
			$("#productTitle").text(title);
			if(data && data.length>0&& data[0].url){
				$("#imgLegend").attr("src",data[0].legendUrl?data[0].legendUrl:"http://10.226.120.45:8091/TJ/tianjin/resources/business/zhfx/skjc/kstwin/img/transparent.png");
				$("#animatImg").attr("src",data[0].url);
			}else{
				$("#imgLegend").attr("src","http://10.226.120.45:8091/TJ/tianjin/resources/business/zhfx/skjc/kstwin/img/transparent.png");
				$("#animatImg").attr("src","http://10.226.120.45:8091/TJ/tianjin/resources/business/zhfx/skjc/kstwin/img/noData.png");
			}
		},
        showecpic:function(proInfo){
            let qbTime = new Date(proInfo.time+":00").format("yyMMddhh");
            $("#imgArea,.imgArea_top,#imgArea_imgLegend").hide();
            $("#eccontain").show();
            let url = `http://10.1.64.146/mtfpy/circu/fcst?name=${proInfo.ele.ele_id}&mode=EC&step=12&initTime=${qbTime}&fcstTime=${proInfo.clickTime}&bounds=73_136_18_54&mproj=latlon&borders=CHINA&timeStamp=${new Date().getTime()}&watermark=0&logo=1&only_cma=1`
            $("#ecpic").attr("src",url);
        },
        // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro == null) return;
            var proInfo = that.getProInfo(this.selectedPro);
            that.getPicData(proInfo);
        },
        getPicData: function (proInfo, timeArr) {
            var that = this;
			let mode = $(".product-zcqfx-tab .active").data("model").id;
            if(mode == "ecjihe"){
                //查询图片数据
               
                var time = $(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00'
                var param = {
                    productID: proInfo.ele.ele_id,
                    productNM: proInfo.ele.ele_name,
                    queryTime: time,
                    forecastTime: time,
                    interval: proInfo.ele.interval,
                    areaCD: 'ADCN',
                    height: proInfo.ele.height?proInfo.ele.height:'0',
                    period: proInfo.ele.interval?proInfo.ele.interval:'3',
                    modeType: 'ECJIHE',
                    mode: proInfo.ele.models,
                    unit: proInfo.ele.unit,
                    areaList: 'ADCN',
                    dataType: '1',
                    isRain: 'true'
                }
                if(that.selectedPro.thred){
                    param.thHoldVla = that.selectedPro.thred;
                }
                $.ajax({
                    url: '/TJ/zhfx/szyb/plane/getProducts.do',
                    type: 'POST',
                    dataType: 'json',
                    data: param,
                }).done(function (res) {
                    that.picData = res.params.data;
                    that.initPlayList(proInfo);
                    //that.showpic(that.picData[0].time);
                    setTimeout(()=>{
                        $("#a-m-timeline .cafe-tl-item:eq(0)").click();
                    },500)
                })
            }else{
                that.initPlayList(proInfo);
                setTimeout(() => {
                    if (mode === 'ece6f') {
                        $("#a-m-timeline .cafe-tl-item:eq(0)").click();
                    } else {
                        $("#a-m-timeline .cafe-tl-item:eq(1)").click();
                    }
                }, 500)
                // let qbTime = $(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00';
                // proInfo.clickTime = new Date(qbTime).format('yyMMddhh');
                // that.showecpic(proInfo);
                // $.ajax({
                //     url: 'http://10.1.64.146/mtfpy/circu/fcst',
                //     type: 'get',
                //     dataType: 'blob',
                //     data: {
                //         name:proInfo.ele.ele_id,
                //         mode:"EC",
                //         step:12,
                //         initTime:"24091908",
                //         fcstTime:"24091908",
                //         bounds:"73_136_18_54",
                //         mproj:"latlon",
                //         borders:"CHINA",
                //         timeStamp:new Date().getTime(),
                //         watermark:0,
                //         logo:1,
                //         "only_cma":1
                //     },
                // }).done(function (res) {
                //     debugger
                //     const blob = new Blob([res],{})
                // })
            }
			
        },
       
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            
        },
        
        getProInfo: function (ele) {
            var height = ele.height != undefined ? ele.height : '';
            var name = $('.product-zcqfx-tab li.active').data('model').name;
            name += '_' + height + ele.ele_name;
            var time = $(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'zcqfx',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-zcqfx-list").off('click').on('click', 'li', function () {
                $(".isShowDataAnysis").removeClass('isShowDataAnysis');
                that.isShowDataAnalysis = false;
                var pro = $(this).data('pro');
                $("#modal_" + pro.ele_id).remove();
                $("#modal_" + pro.ele_id + '_pro').remove();
                $("#modal_product_pic").remove();
				if(!$(this).hasClass("active")) {
                    if (pro.type != 'heatingConsultation') {
                        $(".product-zcqfx-list li.active").removeClass("active");
                        $(".product-zcqfx-list td.active").removeClass("active");
                    } else {
                        if (pro.ele_type == 'element') {
                            $(this).siblings().removeClass('active');
                            if (pro.ele_id === 'TMP') {
                                $('#ysq').hide();
                                // $(this).siblings().removeClass('active');
                            } else {
                                $('#ysq').show();
                                // $('#TMP').removeClass('active');
                            }
                        }
                        
                        if (pro.ele_type == 'station') {
                            $(this).siblings().removeClass('active');
                        }

                        let elementPro = $('#heatingConsultationElement li.active');
                        if (elementPro.length && elementPro.data('pro').ele_id === 'maxVal,minVal,avgVal' && pro.ele_type == 'source') {
                            $(this).siblings().removeClass('active');
                        }
                    }
					
                    $(this).addClass("active");
                    $(this).closest('.product-item').siblings().find('.product-pic-tab li').removeClass("active");
                    if (pro.interval) {
                        $(".product-zcqfx-interval li").addClass('disabled');
                        $(".product-zcqfx-interval li[interval=" + pro.interval + "]").addClass('active').removeClass('disabled').siblings().removeClass('active');
                    }
					$(".addition_condition_title").hide();
					$(".addition_condition_container").hide();
					if(pro.group_needthrad){	 
                        $(".addition_condition_item").removeClass("active");
                        $(this).closest(".product-item").find(".addition_condition_title").show().end().find(".addition_condition_container").show();
                        $(this).closest(".product-item").find(".addition_condition_item").each(function (index,item) {
                        if($(item).attr("item").indexOf(pro.ele_id) == -1){
                            $(item).hide();
                        }else{
                            $(item).show();
                        }
                        })
						$(this).closest(".product-item").find(".addition_condition_item:visible:eq(0)").addClass("active");
						pro.thred = $(this).closest(".product-item").find(".addition_condition_item.active").attr("val");
					}
                    that.selectedPro = pro;
                    var proInfo = that.getProInfo(pro);
                    that.getPicData(proInfo);
                } else {
                    if (pro.type === 'heatingConsultation') {
                        if (pro.ele_type == 'element') {
                            let elementPro = $('#heatingConsultationElement li.active');
                            if (elementPro.length > 1) {
                                $(this).removeClass("active");
                            }
                        }

                        if (pro.ele_type == 'source') {
                            let sourcetPro = $('#heatingConsultationSource li.active');
                            if (sourcetPro.length > 1) {
                                $(this).removeClass("active");
                            }
                        }

                        if (pro.ele_type == 'station') {
                            let stationPro = $('#heatingConsultationStation li.active');
                            if (stationPro.length > 1) {
                                $(this).removeClass("active");
                            }
                        }

                        that.selectedPro = pro;
                        var proInfo = that.getProInfo(pro);
                        that.getPicData(proInfo);
                        
                        // $(this).removeClass("active");
                        // if (pro.ele_type == 'source') {
                        //     let elementPro = $('#heatingConsultationElement li.active');
                        //     let arrEle = [];
                        //     for (let i = 0; i < elementPro.length; i++) {
                        //         arrEle.push($(elementPro[i]).data('pro').ele_id);
                        //     }
                        //     if (arrEle.includes('TMP')) {
                        //         let sourcetPro = $('#heatingConsultationSource li.active');
                        //         if (sourcetPro.length > 1) {
                        //             $(this).removeClass("active");
                        //         }
                        //     }
                        // }

                        // if (pro.ele_type == 'element') {
                        //     if (pro.ele_id != 'TMP') {
                        //         let elementPro = $('#heatingConsultationElement li.active');
                        //         if (elementPro.length > 1) {
                        //             $(this).removeClass("active");
                        //         }
                        //     }
                        // }
                    }
                }
                if (pro.iframeSrc) {
                    that.iframeSrc = pro.iframeSrc;
                    $('#kstAnimatSet').hide();

                    // pro.type === 'heatingConsultation' && that.changeHeatingConsultationIframeSrc();
                } else {
                    that.iframeSrc = '';
                    $('#kstAnimatSet').show();
                    $('.product-zcqfx-pic-iframe').hide();
                }
            }).on('click', 'td', function () {
                that.count++;
                $(this).data('pro').count = that.count;
                var pro = $(this).data('pro');
				$(".addition_condition_title").hide();
				$(".addition_condition_container").hide();
                if (!pro) return;
                let modeId = $(".product-zcqfx-tab li.active").data('model').id;
                let proInfo = that.getProInfo(pro);
                if (!$(this).hasClass("active")) {
                    $(".product-zcqfx-list li.active").removeClass("active");
                    if (['eda', 'eda2'].includes(pro.ele_id)) {
                        $('tr').not('#eda, #eda2').find('td').removeClass('active');
                        var prev = $(this).siblings('td.active');
                        if (prev.length > 0) {
                            prev.removeClass('active');
                        }
                    } else {
                        $(".product-zcqfx-list td.active").removeClass("active");
                    }
					$(this).addClass('active');
					if (pro.interval) {
						$(".product-zcqfx-interval li").addClass('disabled');
						$(".product-zcqfx-interval li[interval=" + pro.interval + "]").addClass('active').removeClass('disabled').siblings().removeClass('active');
					}
					that.selectedPro = pro;
                    if (['ecjh', 'ecc6f', 'ece6f'].includes(modeId)) {
                        that.iframeSrc = pro.iframeSrc;
                        $('#kstAnimatSet').hide();
                        that.getPicData(proInfo);
                    } else {
                        $('#kstAnimatSet').show();
                        $('.product-zcqfx-pic-iframe').hide();
                        that.getPicData(proInfo);
                    }
                } else {
                    if (['ecjh', 'ecc6f', 'ece6f'].includes(modeId)) {
                        that.selectedPro = {};
                        $(this).removeClass('active');
                        that.changeIframeSrc();
                    }
                }
            }).on('click','.addition_condition_item',function(){
				if(!$(this).hasClass("active")){
					$(this).addClass("active").siblings().removeClass("active");
					var pro = $(this).closest(".product-item").find("li.active").data('pro');
					pro.thred = $(this).attr("val");
					that.selectedPro = pro;
                    var proInfo = that.getProInfo(pro);
                    that.getPicData(proInfo);
				}
			})
			
            // 预报时间间隔
            $(".product-zcqfx-interval").delegate('li', 'click', function () {
                if ($(this).hasClass('disabled')) return;
                $(this).addClass("active").siblings().removeClass("active");
                var interval = Number($(this).attr('interval')) * 60;
                that.getMultiGridData();
            })
            // 最近起报时间
            $(".product-zcqfx-datechange").delegate('li', 'click', function () {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');
                $(".product-zcqfx-datepicker #date").IDatePicker().setVal(time);
                that.getMultiGridData();
            })
            $('.product-zcqfx-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                $(".product-zcqfx-datepicker #date").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $(".product-zcqfx-datepicker #date").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $(".product-zcqfx-datepicker #date").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            });   

            $('input[name="handle"]').change(function() {
                that.changeIframeSrc();
            });

            $(".product-zcqfx-tab li").on('click', function (e) {
                if ($(this).data('model').id === 'ece6f') {
                    $('.handle-btns').removeClass('hide');
                } else {
                    $('.handle-btns').addClass('hide');
                }

                if (['ecc6f', 'ece6f'].includes($(this).data('model').id)) {
                    $('.iPicker-hourWrap ul li[channel="20"]').hide();
                } else {
                    $('.iPicker-hourWrap ul li[channel="20"]').show();
                }
            });

            $(".product-zcqfx-tab li").first().click();
        },
        //给中长期分析传递参数
        changeIframeSrc() {
            let that = this;
            console.log('selectedPro======>', that.selectedPro);
            let params = {};
            let modeId = $(".product-zcqfx-tab li.active").data('model').id;
            if (['ecjh', 'ecc6f', 'ece6f'].includes(modeId)) {

                let elementPro = $('#height td.active');
                let arrEle = [];
                for (let i = 0; i < elementPro.length; i++) {
                    arrEle.push($(elementPro[i]).data('pro'));
                }

                let element = this.selectedPro.ele_id || '';
                let height = this.selectedPro.height || '';
                let count = '';
                if (arrEle.length) {
                    element = arrEle.map(el => el.ele_id).join();
                    height = arrEle.map(el => el.height).join();
                    count = arrEle.map(el => el.count).join();
                }
                params = {
                    type: modeId,
                    queryTime: that.time,
                    period: modeId === 'ecjh' ? `${that.period}`.padStart(3, '0') : modeId === 'ece6f' ? that.period : Number(that.period / 24),
                    element,
                    height,
                    currentTime: that.playList.getCurTime(),
                    count
                }

                if (modeId === 'ece6f') {
                    params.handleType = $('input[name="handle"]:checked').val();
                }
            } else {
                params = {
                    type: 'extendedForecast',
                    time: that.time,
                    period: that.period,
                    element: that.selectedPro.ele_id,
                    cluster: ['tp_cluster', 'gh500_cluster'].includes(that.selectedPro.ele_id) ? that.currentCluster : '',
                    queryTime: that.time,
                    currentTime: that.playList.getCurTime()
                }
            }

            const searchParams = new URLSearchParams();
            Object.keys(params).forEach(key => searchParams.append(key, params[key]));

            $('.product-zcqfx-pic-iframe').show();
            $('.product-zcqfx-pic-iframe').attr('src', `${this.iframeSrc}home?${searchParams.toString()}`);
        },
        //获取ap聚类-降水、高度场内容
        getTpClusterList(time) {
            let that = this;
            if (this.targetId !== 'ap') return;
            $.ajax({
                url: that.router.clusterList,
                // url: 'http://101.126.153.10:9090/raw/ysqMakeImg/clusterList',
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    time,
                    // time: 20241128080000,
                    element: 'tp_cluster',
                    period:  that.period,
                    cluster: 'cluster01'
                }
            }).done(function (res) {
                that.currentCluster = '';
                if (res.code === 0 && res.data) {
                    that.apTpClusterList = ['', ...res.data];
                    $('#apGh500ClusterList').empty().append('<option value="" disabled selected>请选择</option>');
                    let $select = $('#apTpClusterList').empty();
                    that.apTpClusterList.forEach((el, index) => {
                        let $option = null;
                        if (index === 0) {
                            $option = $(`<option value="${el}" disabled>请选择</option>`);
                        } else if (index === 1) {
                            $option = $(`<option value="${el}" selected>${el}</option>`);
                            that.currentCluster = el;
                        } else {
                            $option = $(`<option value="${el}">${el}</option>`);
                        }
                        $select.append($option);
                    });
                } else {
                    console.error('获取地面降水列表失败');
                }
            });
        },
        getGh500ClusterList(time) {
            let that = this;
            if (this.targetId !== 'ap') return;
            $.ajax({
                url: that.router.clusterList,
                // url: 'http://101.126.153.10:9090/raw/ysqMakeImg/clusterList',
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    time,
                    // time: 20241126200000,
                    element: 'gh500_cluster',
                    period:  that.period,
                    cluster: 'cluster01'
                }
            }).done(function (res) {
                that.currentCluster = '';
                if (res.code === 0 && res.data) {
                    that.apGh500ClusterList = ['', ...res.data];
                    $('#apTpClusterList').empty().append('<option value="" disabled selected>请选择</option>');
                    let $select = $('#apGh500ClusterList').empty();
                    that.apGh500ClusterList.forEach((el, index) => {
                        let $option = null;
                        if (index === 0) {
                            $option = $(`<option value="${el}" disabled>请选择</option>`);
                        } else if (index === 1) {
                            $option = $(`<option value="${el}" selected>${el}</option>`);
                            that.currentCluster = el;
                        } else {
                            $option = $(`<option value="${el}">${el}</option>`);
                        }
                        $select.append($option);
                    });
                } else {
                    console.error('获取高空高度场列表失败');
                }
            });
        },
        //给中长期分析-会商传递参数
        changeHeatingConsultationIframeSrc() {
            let params = {};
            let elementPro = $('#heatingConsultationElement li.active');
            let source = $('#heatingConsultationSource li.active');
            let station = $('#heatingConsultationStation li.active');

            let arrEle = [];
            for (let i = 0; i < elementPro.length; i++) {
                arrEle.push($(elementPro[i]).data('pro').ele_id);
            }

            let arrSource = [];
            for (let i = 0; i < source.length; i++) {
                arrSource.push($(source[i]).data('pro').ele_id);
            }

            var time = new Date($(".product-zcqfx-datepicker #date").IDatePicker().getVal() + ':00').format("yyyyMMddhh0000");
            if (arrEle.includes('TMP')) {
                params = {
                    element: 'TMP',
                    queryTime: time, //20241126200000
                    source: arrSource.join(),
                    lon: station.length ? station.data('pro').lon : '',
                    lat: station.length ? station.data('pro').lat : '',
                    station: station.length ? station.data('pro').ele_name : ''
                }
            } else {
                params = {
                    element: arrEle.join(),
                    queryTime: time, //20241126200000
                    // source: source.length ? source.data('pro').ele_id : '',
                    source: arrSource.join(),
                    lon: station.length ? station.data('pro').lon : '',
                    lat: station.length ? station.data('pro').lat : '',
                    station: station.length ? station.data('pro').ele_name : ''
                }
            }

            const searchParams = new URLSearchParams();
            Object.keys(params).forEach(key => searchParams.append(key, params[key]));

            console.log('changeHeatingConsultationIframeSrc======>', searchParams.toString());

            $('#kstAnimatSet').hide();
            $('.product-zcqfx-pic-iframe').show();
            $('.product-zcqfx-pic-iframe').attr('src', `${this.iframeSrc}heatingConsultation?${searchParams.toString()}`);
        }
    }
    if (typeof call === 'function') {
        CafeJS.zcqfx = zcqfx;
        call(zcqfx);
    }
    window.zcqfx = zcqfx;
})(function (zcqfx) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        zcqfx.init();
    });
});
